package config;

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**   时间格式配置类
 * @author xiehaidong
 */
@Configuration
public class LocalDateTimeConfig {
    /**
     *    将内容序列化（LocalDateTime->String)
     * @return 服务端返回给客户端内容
     */
    @Bean
    public LocalDateTimeSerializer localDateTimeSerializer(){
        return  new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }


    /**
     *    反序列化（String-LocalDateTime
     * @return  客户端传入服务端数据
     */
    @Bean
    public LocalDateTimeDeserializer localDateTimeDeserializer(){
        return  new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     *    配置自定义序列化和反序列化
     * @return
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer(){
        return builder -> {
            builder.serializerByType(LocalDateTime.class, localDateTimeSerializer());
            builder.deserializerByType(LocalDateTime.class, localDateTimeDeserializer());
        };
    }
}
